package com.myCode.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOServer {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务启动成功");
        while (!serverSocket.isClosed()){
            // 这里线程是阻塞的 不接受其他客户端的连接
            Socket request = serverSocket.accept();
            System.out.println("收到新连接：" + request.toString());

            try {
                InputStream inputStream = request.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                String msg = null;
                while ((msg = reader.readLine()) != null){
                    if (msg.length() == 0){
                        break;
                    }
                    System.out.println(msg);
                }
                System.out.println("收到数据，来自：" + request.toString());
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try {
                    request.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
    }
}
